<script>
    // 进销存 仓库管理表单
    Vue.component('stock-balance-form', {
        template: `
<el-dialog :visible.sync="dialogShow" width="1000px" @close="closeModal" :close-on-click-modal="false" :close-on-press-escape="false">
    <h3 slot="title">
        <span v-if="optType=='in'">产品入库</span>
        <span v-else-if="optType=='out'">产品出库</span>
        <span v-else-if="optType=='trans'">产品调拨</span>
    </h3>
    <el-form ref="form" :rules="formRules" :model="balanceForm" label-width="80px">

    <div v-if="optType=='in'">
     <el-form-item prop="house_id" label="调入仓库">
        <el-select placeholder="请选择调入仓库" size='medium' v-model="balanceForm.house_id"  @change="houseSelect">
            <el-option
                v-for="item in stockWareHouseList"
                :key="item.id"
                :label="item.title"
                :value="item.id">
            </el-option>
        </el-select>
     </el-form-item>
    </div>

    <div v-else-if="optType=='out'">
     <el-form-item prop="house_id" label="调出仓库">
        <el-select placeholder="请选择调出仓库" size='medium' v-model="balanceForm.house_id"  @change="houseSelect">
            <el-option
                v-for="item in stockWareHouseList"
                :key="item.id"
                :label="item.title"
                :value="item.id">
            </el-option>
        </el-select>
     </el-form-item>
    </div>

    <div v-else-if="optType=='trans'">
        <el-row>
        <el-col span="12">
            <el-form-item prop="house_id" required label="调入仓库">
                    <el-select placeholder="请选择调入仓库" size='medium' v-model="balanceForm.house_id"  @change="houseSelect">
                        <el-option
                            v-for="item in stockWareHouseList"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
        </el-col>
        <el-col span="12">
            <div v-if="optType=='trans'">
                 <el-form-item prop="house_id_from" required label="调出仓库">
                    <el-select placeholder="请选择调出仓库" size='medium' v-model="balanceForm.house_id_from"  @change="houseFromSelect">
                        <el-option
                            v-for="item in stockWareHouseList"
                            :key="item.id"
                            :label="item.title"
                             :disabled="item.id == balanceForm.house_id"
                            :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </div>
        </el-col>
        </el-row>
    </div>

    <el-row>
        <el-col span="12">
             <el-form-item label="项目">
                <el-select placeholder="选择项目" clearable filterable default-first-option v-model="balanceForm.project_id" size='medium'>
                    <el-option
                        v-for="item in projectList"
                            :key="item.id"
                            :label="item.title"
                            :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>
        </el-col>
        <el-col span="12">
            <el-form-item label="时间" style="margin-right:0;">
                <el-date-picker class="datePicker" v-model="balanceForm.tally_date" placeholder="选择日期" value-format="yyyy-MM-dd"></el-date-picker>
            </el-form-item>
        </el-col>
    </el-row>

    <el-form-item label="备注">
        <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" maxlength="255" show-word-limit placeholder="备注" v-model="balanceForm.memo" class="memoText"></el-input>
    </el-form-item>
    <!---复杂的表格 可动态选择产品--->
     <el-form-item label="">
     <el-table
      :data="productListData"
      style="width: 100%">
      <el-table-column
        prop="product_info"
        label="产品" >
          <template slot-scope="scope">
            <div>
             <el-select
                :value="productListData[scope.$index]['product_title']"
                filterable
                remote
                placeholder="请输入产品关键词"
                :remote-method="productSearch"
                @change="productSelect($event,scope.row,scope.$index)"
                size="mini"
                >
                <el-option
                  v-for="item in productFilterData"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id">
                </el-option>
              </el-select>
            </div>
          </template>
      </el-table-column>
      <el-table-column
        prop="unit"
        label="单位">
         <template slot-scope="scope">
            <span>{{scope.row['product_unit']}}</span>
          </template>
      </el-table-column>
      <el-table-column
        prop="pure_num"
        label="库存">
         <template slot-scope="scope">
            <span>{{scope.row['pure_num']}}</span>
          </template>
      </el-table-column>
      <el-table-column
        prop="cost_price"
        label="成本价">
        <template slot-scope="scope">
            <el-input v-model="productListData[scope.$index]['cost_price']" size="mini" v-if="productListData[scope.$index]['product_id']" type="number" min="0" step="0.01" @blur="validPrice($event,scope.$index)"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="num"
        label="数量">
        <template slot-scope="scope">
          <el-input v-model="productListData[scope.$index]['num']" size="mini" v-if="productListData[scope.$index]['product_id']" type="number" min="0" step="1" :max="calcMax(productListData[scope.$index]['pure_num'])" @blur="validNum($event,scope.$index)"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        prop="money"
        label="金额">
        <template slot-scope="scope">
            <span>{{scope.row['money']}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="opt"
        label="">
        <template slot-scope="scope">
          <el-button type="info" icon="el-icon-delete" circle  @click="delProductRow(scope.$index)" size="mini"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <p class="opt-row">
        <i class="el-icon-plus"></i>
        <el-button type="text" @click="addProductRow">添加一行</el-button>
    </p>
    <p class="t-r">
    数量合计：{{productTotalNum}}
    金额合计：{{productTotalMoney}}
    </p>
    </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
    <el-button @click="closeModal">取 消</el-button>
    <el-button type="primary" @click="handleFormSubmit">确 定</el-button>
    </div>
</el-dialog>
    `,
        props: ['dialog-show', 'balance-type'],
        computed: {
            currentTallyId() {
                return this.$store.state.currentTallyId
            },
            currentTally() {
                return this.$store.state.currentTally
            },
            projectList() {
                return this.$store.state.projectList
            },
            stockWareHouseList() {
                return this.$store.state.stockWareHouseList
            },
            stockProductList() {
                return this.$store.state.stockProductList
            }
        },
        watch: {
            dialogShow: {
                handler(newVal) {
                },
                deep: true,
                immediate: true
            },
            balanceType: {
                handler(newVal) {
                    this.optType = newVal
                },
                deep: true,
                immediate: true
            }
        },
        data: function () {
            return {
                balanceForm: {},
                optType: 'in', // 操作类型
                formRules: {
                    house_id: [
                        {required: true, message: '请选择仓库', trigger: 'blur'}
                    ],
                },
                productFilterData:[], // 过滤后显示的产品列表
                productListData: [
                    {},
                ], // 准备的产品列表数据
                productTotalNum:0, // 统计数据
                productTotalMoney:0,

                stockHouseProductList:[], // 某仓库下可供选择的产品列表
            }
        },
        mounted:function(){
            if(this.optType === 'in') {
                this.productFilterData = this.stockHouseProductList
            }else {
                this.productFilterData = [] // 依赖选择仓库触发
            }
        },
        methods: {
            closeModal() {
                this.$emit('modalClose', '')
            },
            // 重置
            resetForm() {
                this.productListData = [{}]
                this.balanceForm = {}
                this.productTotalNum = 0
                this.productTotalMoney = 0
            },
            calcMax(num) {
                if(!num) return '';
                if(isNaN(num)) {
                    return '';
                }else {
                    return parseFloat(num)
                }
            },
            productSelect(productId, row, index) {
                // 获取产品信息最新的 然后拼接到
                let that = this
                let item = this.productFilterData.find((iv)=>{
                    return iv.id === productId;
                });
                let newValue = JSON.parse(JSON.stringify(this.productListData[index]))
                newValue['product_id'] =  item['id']
                newValue['product_title'] =  item['title']
                newValue['pure_num'] = item['pure_num'] ? item['pure_num'] : '-'
                newValue['num'] = 1

                that.getProductInfo(productId).then((prodInfo) => {
                    newValue['product_spec'] =  prodInfo['spec']
                    newValue['product_unit'] =  prodInfo['unit']
                    newValue['cost_price'] =  prodInfo['cost_price']
                    newValue['sale_price'] =  prodInfo['sale_price']
                    newValue['purchase_price'] =  prodInfo['purchase_price']
                    // 刷新数据
                    this.$set(this.productListData,index,newValue)
                    this.calRowMoney(index)
                })
            },
            getProductInfo(productId) {
                let that = this
                let getUrl = '/api/stock-product/info'
                let params = {
                    tally_id : that.currentTallyId,
                    product_id : productId
                }
                return new Promise((resolve, reject) => {
                    axios.get(getUrl,{
                        method: 'get',
                        headers: {'token': loginToken},
                        params: params
                    }).then(function(res) {
                        if(res.data.status === 'success'){
                            resolve(res.data.data)
                        }else{
                            resolve({})
                        }
                    })
                }).catch(err=>{
                    reject()
                })
            },
            validPrice(e,index) {
                let number = this.productListData[index]['cost_price']
                number = parseFloat(number).toFixed(2)
                this.productListData[index]['cost_price'] = number
                this.calRowMoney(index)
            },
            validNum(e,index) {
                let number = this.productListData[index]['num']
                number = parseFloat(number).toFixed(2)
                this.productListData[index]['num'] = number
                this.calRowMoney(index)
            },
            // 计算分录金额
            calRowMoney(index) {
                let price = this.productListData[index]['cost_price']
                let num = this.productListData[index]['num']
                let pureNum = this.productListData[index]['pure_num']
                // let num = pure_num;
                if(!isNaN(pureNum) && parseFloat(num) > parseFloat(pureNum) ){
                    num = pureNum
                    this.productListData[index]['num'] = pureNum
                }
                this.productListData[index]['money'] = (price * num ).toFixed(2)
                this.calTotal()
            },
            // 计算总计金额
            calTotal() {
                let totalNum = 0
                let totalMoney = 0
                this.productListData.forEach((item) => {
                    if(item['product_id']) {
                        totalNum = totalNum + parseFloat(item['num'])
                        totalMoney = totalMoney + parseFloat(item['money'])
                    }
                })
                this.productTotalNum = parseFloat(totalNum).toFixed(2)
                this.productTotalMoney = parseFloat(totalMoney).toFixed(2)
            },
            houseSelect(houseId) {
                let item = this.stockWareHouseList.find((iv)=>{
                    return iv.id === houseId;
                });
                this.balanceForm['house_id'] = item['id'];
                this.balanceForm['house_title'] = item['title'];
                // 获取该仓库下的库存产品列表
                if(this.optType === 'in') {
                    this.getProductList() // 全局产品
                }else if(this.optType === 'out') {
                    this.getHouseProductList(item['id']) // 仓库下产品
                    this.productListData = [{}]   // 清空产品数据
                }
                if(this.optType === 'trans' && item['id'] === this.balanceForm['house_id_from']){
                    this.balanceForm['house_id_from'] = ''
                    this.balanceForm['house_title_from'] = ''
                }
            },
            getProductList() {
                let that = this
                let getUrl = '/api/stock-product/all'
                let params = {
                    tally_id : that.currentTallyId,
                }
                axios.get(getUrl,{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: params
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        that.stockProductList = res.data.data
                        that.productFilterData = res.data.data
                    }else{
                        that.productFilterData = []
                    }
                })
            },
            getHouseProductList(houseId) {
                let that = this
                let getUrl = '/api/stock-warehouse/product-all'
                let params = {
                    tally_id : that.currentTallyId,
                    house_id : houseId
                }
                axios.get(getUrl,{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: params
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        that.stockProductList = res.data.data
                        that.productFilterData = res.data.data
                    }else{
                        that.productFilterData = []
                    }
                })
            },
            houseFromSelect(houseId) {
                let item = this.stockWareHouseList.find((iv)=>{
                    return iv.id === houseId;
                });
                this.balanceForm['house_id_from'] = item['id'];
                this.balanceForm['house_title_from'] = item['title'];
                this.getHouseProductList(item['id']) // 仓库下产品
                this.productListData= [{}]   // 清空产品数据
                if(item['id'] === this.balanceForm['house_id']){
                    this.balanceForm['house_id'] = ''
                    this.balanceForm['house_title'] = ''
                }
            },
            productSearch(query) {
                let that = this
                if(query === '') {
                    that.productFilterData = that.stockProductList
                }else {
                    if(this.optType === 'in') {
                        this.productSearchGlobal(query)  // 全局产品搜索
                    }else {
                        this.productSearchHouse(query)  // 仓库下产品搜索
                    }
                }
            },
            productSearchGlobal(keywords) {
                let that = this
                let getUrl = '/api/stock-product/lists'
                let params = {
                    tally_id : that.currentTallyId,
                    keywords : encodeURIComponent(keywords)
                }
                axios.get(getUrl,{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: params
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        that.productFilterData = res.data.data.data
                    }else{
                        that.productFilterData = []
                    }
                })
            },
            productSearchHouse(keywords) {
                let that = this
                let getUrl = '/api/stock-warehouse/product-search'
                let params = {
                    tally_id : that.currentTallyId,
                    house_id : that.optType=='trans' ? that.balanceForm['house_id_from']:  that.balanceForm['house_id'],
                    keywords : encodeURIComponent(keywords)
                }
                axios.get(getUrl,{
                    method: 'get',
                    headers: {'token': loginToken},
                    params: params
                }).then(function(res) {
                    if(res.data.status === 'success'){
                        that.productFilterData = res.data.data.data
                    }else{
                        that.productFilterData = []
                    }
                })
            },
            addProductRow() {
                this.productListData.push({})
            },
            delProductRow(index)  {
                this.productListData.splice(index,1)
                this.calTotal()
            },
            handleFormSubmit() {
                let that = this
                let postUrl;
                if(that.productListData.length < 1) {
                    that.$message({
                        type: 'error',
                        message: '请先填写完整产品信息'
                    })
                    return false;
                }
                if (that.optType === 'in') {
                    postUrl = '/api/stock-balance/in-house'
                }else if (that.optType === 'out') {
                    postUrl = '/api/stock-balance/out-house'
                }else if (that.optType === 'trans') {
                    postUrl = '/api/stock-balance/transfer-house'
                }
                that.balanceForm.tally_id = that.currentTallyId
                that.balanceForm.product_detail = that.productListData
                axios.post(postUrl, that.balanceForm, {
                    headers: {'token': loginToken},
                }).then(function (res) {
                    if (res.data.status === 'success') {
                        that.$message({
                            type: 'success',
                            message: '数据保存成功'
                        });
                        that.$emit('modalClose', 'refresh')
                    } else {
                        that.$message({
                            type: 'error',
                            message: '解析数据失败:' + res.data.error_message
                        })
                    }
                })
            },
        }
    })
</script>
<style>
    .memoText {
        width: 300px;
    }
    .t-r {
        text-align: right;
    }
    .opt-row{
        color: #409EFF;
    }
</style>
